<template>
  <div>
    <!-- 搜索栏 -->
    <el-form v-show="showSearch" :inline="true" :model="queryParams">
      <el-form-item label="姓名">
        <el-input v-model="queryParams.name" clearable placeholder="请输入老师姓名"
                  style="width: 150px" @input="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <svg-icon icon-file-name="white-search" style="color: #1abc9c"></svg-icon>
          搜索
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <el-row :gutter="10" style="margin-bottom: 15px">
      <el-col :span="1.5">
        <el-button :disabled="teacherIdList.length === 0" icon="Delete" plain type="danger"
                   @click="handleBatchDelete">批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-plus" plain type="primary" @click="teacherInfoDialogVisible = true; isEditing = false;">
          新增
        </el-button>
      </el-col>
      <refresh-and-hide @refresh="handleRefresh" @toggle-search="handleToggleSearch"/>
    </el-row>
    <div class="scroll-container">
      <!-- 表格展示 -->
      <el-table v-loading="loading" :data="teacherList" border @sort-change="handleSortChange"
                @selection-change="handleSelectionChange">
        <!-- 表格选择列 -->
        <el-table-column align="center" type="selection" width="55"></el-table-column>
        <!--缩略图-->
        <el-table-column align="center" label="头像" prop="avatarUrl" width="180">
          <template #default="scope">
            <el-image :lazy="true" :src="scope.row.avatarUrl" class="image-cover" fit="cover">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" label="姓名" prop="name" ></el-table-column>
        <el-table-column align="center" label="教工号" prop="teacherNum" ></el-table-column>
        <el-table-column align="center" label="所授课程数" prop="courseNum" sortable="custom" >
        </el-table-column>
        <el-table-column align="center" label="注册时间" prop="createTime" sortable >
          <template #default="scope">
            <div class="time">
              <svg-icon icon-file-name="time"></svg-icon>
              <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 更新时间 -->
        <el-table-column align="center" label="信息更新时间" prop="updateTime" sortable width="130">
          <template #default="scope">
            <div class="time">
              <svg-icon icon-file-name="time"></svg-icon>
              <span style="margin-left: 10px">{{ scope.row.updateTime }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column align="center" label="操作" width="220">
          <template #default="scope">
            <el-button class="sdf" link type="primary" @click="handleEdit(scope.row)">
              <svg-icon icon-file-name="edit"></svg-icon>
              编辑
            </el-button>
            <el-button class="sd" link type="danger" @click="handleDelete(scope.row.teacherId)">
              <svg-icon icon-file-name="delete"></svg-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <pagination v-if="total > 0" :limit="pagInfo.pageSize" :page="pagInfo.currentPage" :total="total"
                style="float: right;" @pagination="getTeacherInfoList"
                @update_limit="pagInfo.pageSize = $event"
                @update_page="pagInfo.currentPage = $event"/>
    <el-dialog :visible.sync="teacherInfoDialogVisible" :title="GTitle" width="50%">
      <el-form ref="studentInfoForm" :model="teacherInfoForm" :rules="teacherRules">
        <el-form-item :label-width="formLabelWidth" label="姓名" prop="name">
          <el-input v-model="teacherInfoForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="工号" prop="teacherNum">
          <el-input v-model="teacherInfoForm.teacherNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="头像">
          <ImageUpload ref="teacherImage" :limit="1" @update-file-list="handleUpdateTeacherAvatar"></ImageUpload>
        </el-form-item>
        <el-form-item v-if="!isEditing" :label-width="formLabelWidth" label="密码" prop="password">
          <el-input v-model="teacherInfoForm.password" type="password" autocomplete="off" placeholder="请输入密码"></el-input>
        </el-form-item>
        <!-- 新增修改密码项 -->
        <el-form-item v-else :label-width="formLabelWidth" label="修改密码:">
          <el-button @click="showTeacherPasswordInput = !showTeacherPasswordInput">修改密码</el-button>
          <el-input v-if="showTeacherPasswordInput" v-model="teacherInfoForm.password" autocomplete="off"
                    placeholder="请输入新密码" type="password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="teacherInfoDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveTeacherInfo()">保存</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import refreshAndHide from "@/common/refreshAndHide.vue";
import Pagination from "@/common/pagination.vue";
import {
  getTeacherList,
  deleteTeacherOnList, deleteTeacherInfo, addTeacherInfo, editTeacherInfo
} from "@/apis/admin";
import ImageUpload from "@/common/ImageUpload.vue";

export default {
  // 组件注册，允许在模板中使用导入的组件
  components: {
    ImageUpload,
    Pagination, // 分页组件
    refreshAndHide // 刷新和隐藏组件
  },
  // 组件的响应数据对象
  data() {
    return {
      teacherRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度应在 2 到 20 个字符之间', trigger: 'blur' }
        ],
        teacherNum: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{4,10}$/, message: '工号格式不正确，应为4到10位字母或数字', trigger: 'blur' }
        ],
        password: [
          { required: !this.isEditing, message: '请输入密码', trigger: 'blur', condition: () => !this.isEditing },
          { min: 6, max: 20, message: '密码长度应在 6 到 20 个字符之间', trigger: 'blur', condition: () => this.showTeacherPasswordInput }
        ]
      },
      // 控制搜索表单显示的布尔值
      showSearch: true,
      // 搜索参数对象
      queryParams: {
        name: '', // 课程名
      },
      //分页信息
      pagInfo: {
        currentPage: 1,
        pageSize: 10
      },
      // 存储选中的课程ID列表
      teacherIdList: [],
      // 存储课程列表的数组
      teacherList: [],
      // 控制表格加载状态的布尔值
      loading: false,
      // 存储总课程数量的变量
      total: 0,

      isEditing: false, // 是否是编辑状态
      showTeacherPasswordInput:false,
      teacherInfoDialogVisible: false,
      teacherInfoForm: { // 编辑表单的数据模型
        teacherId: '',
        teacherNum: '',
        avatarUrl: '',
        name: '',
        courseNum: '',
        password: ''
      },
      formLabelWidth: '120px', // 表单标签宽度
    };
  },
  methods: {
    saveTeacherInfo() {
      this.$refs.studentInfoForm.validate((valid) => {
        if (valid) {
          if(!this.isEditing){
            let data = {
              teacherNum: this.teacherInfoForm.teacherNum,
              name: this.teacherInfoForm.name,
              avatarUrl: this.teacherInfoForm.avatarUrl,
              password: this.$common.encrypt(this.teacherInfoForm.password)
            }
            addTeacherInfo(data).then(res=>{
              if (res.data.code === 1){
                this.$message({
                  message: "新增成功",
                  type: "success"
                });
                this.teacherInfoDialogVisible = false;
                this.getTeacherInfoList();
              } else {
                this.$message.error(res.data.msg);
              }
            })
          } else {
            let data = {
              teacherId: this.teacherInfoForm.teacherId,
              teacherNum: this.teacherInfoForm.teacherNum,
              name: this.teacherInfoForm.name,
              avatarUrl: this.teacherInfoForm.avatarUrl,
              password: (!this.$common.isEmpty(this.teacherInfoForm.password)) ? this.$common.encrypt(this.teacherInfoForm.password) : null
            }
            editTeacherInfo(data).then(res=>{
              if (res.data.code === 1){
                this.$message({
                  message: "修改成功",
                  type: "success"
                });
                this.teacherInfoDialogVisible = false;
                this.getTeacherInfoList();
              } else {
                this.$message.error(res.data.msg);
              }
            })
          }
        } else {
          this.$message.error('表单中有错误，请修正后再尝试保存');
          return false;
        }
      });
    },
    handleUpdateTeacherAvatar(newFileList) {
      // 使用传递过来的 fileList 更新父组件的 parentFileList
      // 遍历 newFileList 数组
      newFileList.forEach(file => {
        // 将每个文件的 URL 添加到 imageUrls 数组中
        this.teacherInfoForm.avatarUrl = file.url;
      });
    },
    // 处理编辑按钮点击事件
    handleEdit(data) {
      this.isEditing = true;
      this.teacherInfoDialogVisible = true;
      this.teacherInfoForm = data;
      this.$nextTick(()=>{
        this.$refs.teacherImage.fileList = [];
        this.$refs.teacherImage.setFileList(data.avatarUrl);
      })
    },

    // 前端排序函数
    handleSortChange({prop, order}) {
      if (!order) {
        // 如果没有排序顺序，可能是恢复到未排序状态
        this.getTeacherInfoList();
        return;
      }

      // 根据排序信息对 articleList 进行排序
      // articleList 是一个数组，包含要显示在表格中的文章
      this.teacherList.sort((a, b) => {
        if (order === 'ascending') {
          return a[prop] - b[prop]; // 升序排序
        } else {
          return b[prop] - a[prop]; // 降序排序
        }
      });
    },
    // 处理搜索显示/隐藏的逻辑
    handleToggleSearch() {
      this.showSearch = !this.showSearch;
    },
    // 处理刷新数据的逻辑
    handleRefresh() {
      this.getTeacherInfoList();
      this.$message.success('列表已刷新');
    },
    // 搜索课程的方法
    handleQuery() {
      this.loading = true;
      // 重置当前页为第一页
      this.pagInfo.currentPage = 1;
      const pagination = {
        currentPage: this.pagInfo.currentPage,
        pageSize: this.pagInfo.pageSize
      }
      const queryParams = {
        name: this.queryParams.name,
        teacherName: this.queryParams.teacherName,
      }
      const DTOdata = {
        pagination,
        queryParams//只有搜索时才会带上
      }
      getTeacherList(DTOdata).then(res => {
        if (res.data.code === 1) {
          res.data.data.list.forEach((teacher) => {
            teacher.createTime = this.$common.dateFormat(teacher.createTime);
            teacher.updateTime = this.$common.dateFormat(teacher.updateTime);
          });
          this.teacherList = res.data.data.list;
          this.total = res.data.data.total;
          this.loading = false;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    // 处理表格行选择事件
    handleSelectionChange(selection) {
      this.teacherIdList = selection.map(item => item.teacherId);
    },
    //批量删除方法
    handleBatchDelete() {
      if (this.teacherIdList.length === 0) {
        this.$message({
          type: 'info',
          message: '请选择要删除的老师'
        });
        return;
      }
      // 确认弹窗
      this.$confirm('确定要删除选中的老师吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          ids: this.teacherIdList
        }
        // 这里发送删除请求
        deleteTeacherOnList(data).then(res=>{
          if (res.data.code === 1){
            this.$message.success(res.data.data);
            this.getTeacherInfoList();
          } else {
            this.$message.error(res.data.msg);
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 删除单个课程的方法
    handleDelete(id) {
      if (id) {
        this.$confirm('确定要删除该老师吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const data = {
            teacherId:id
          }
          deleteTeacherInfo(data).then(res => {
            if (res.data.code === 1){
              this.$message.success(res.data.data);
              this.getTeacherInfoList();
            } else {
              this.$message.error(res.data.msg);
            }
          })
        }).catch(() => {
          this.$message({
            type: 'warning',
            message: '已取消删除'
          });
        });
      }
    },
    // 获取老师信息列表的方法
    async getTeacherInfoList() {
      this.loading = true;
      const pagination = {
        currentPage: this.pagInfo.currentPage,
        pageSize: this.pagInfo.pageSize
      }
      const queryParams = null;
      const DTOdata = {
        pagination,
        queryParams
      }
      await getTeacherList(DTOdata).then(res => {
        if (res.data.code === 1) {
          res.data.data.list.forEach((course) => {
            course.createTime = this.$common.dateFormat(course.createTime);
            course.updateTime = this.$common.dateFormat(course.updateTime);
          });
          this.teacherList = res.data.data.list;
          this.total = res.data.data.total;
          this.loading = false;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    }
  },
  created() {
    this.getTeacherInfoList();
  },
  computed:{
    GTitle() {
      return this.isEditing ? '编辑老师' : '新增老师'
    }
  }
};
</script>

<style scoped>

.scroll-container {
  max-height: 646px; /* 您可以根据需要调整这个值 */
  overflow-y: auto;
}

.sdf {
  background: transparent;
  border-color: transparent;
  color: #76d7ff;
}

.sd {
  background: transparent;
  border-color: transparent;
  color: #fa1224;
}

.image-cover {
  width: 100px;
  height: 60px;
  border-radius: 5px;
  overflow: hidden;
  cursor: pointer;

  .image-slot {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    color: #909399;
  }
}

.time {
  display: flex;
  align-items: center;
}
</style>

